package com.Nuyoah.demo01.service.serviceImpl;

import com.Nuyoah.demo01.entity.Menu;
import com.Nuyoah.demo01.mappers.MenuMapper;
import com.Nuyoah.demo01.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> buildMenuTree() {
        // 使用Mapper查询所有菜单
        List<Menu> allMenus = menuMapper.selectList(null);
        return allMenus.stream()
                .filter(menu -> menu.getParentMenuId() == -1)
                .peek(menu -> menu.setChildren(getChildren(menu, allMenus)))
                .collect(Collectors.toList());
    }

    private List<Menu> getChildren(Menu parent, List<Menu> all) {
        return all.stream()
                .filter(menu -> parent.getId().equals(menu.getParentMenuId()))
                .peek(menu -> menu.setChildren(getChildren(menu, all)))
                .collect(Collectors.toList());
    }
}
